// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import sceneMediator from "../../framework/sceneMediator";
import gameData from "../gameData";
import mainManage from "../../framework/mainManage";
import Tool from "../../framework/Tool";
import GameConfig from "../../framework/GameConfig";
import AudioManage, {soundList} from "../../framework/AudioManage";

const {ccclass, property} = cc._decorator;

enum Require {
    RECORD_SCREEN = 1,//录屏
    SEE_VIDEO = 2 //看视频
}

enum Rewards {
    REWARD_PET = 1,//奖励宠物
    REWARD_ROLE = 2,//奖励人物
    REWARD_APPLE = 3,//苹果
    LOTTERY_TICKET = 4,//奖券
    REWARD_PET_ROLE = 5, //宠物和人物
    PURPLE_PIECE = 6  //紫色碎片
}

@ccclass
export default class eggWallMediator extends cc.Component {

    @property(cc.Sprite)
    partPic : cc.Sprite[] = [];

    @property(cc.SpriteFrame)
    partPicList : cc.SpriteFrame[] = [];

    @property(cc.Node)
    templateNode : cc.Node = null;

    @property(cc.Node)
    templateItem : cc.Node = null;

    @property(cc.Node)
    contentNode : cc.Node = null;

    @property({type : cc.Node ,displayName : "彩蛋墙"})
    eggWallNode : cc.Node = null;

    @property({type : cc.Node ,displayName : "彩蛋皮肤"})
    skinWallNode : cc.Node = null;

    @property(cc.Node)
    skinWallNodeList : cc.Node[] = [];

    @property({type : cc.Node ,displayName : "兑换码"})
    redeemCodeNode : cc.Node = null;

    @property(cc.Node)
    redeemCodeNodeList : cc.Node[] = [];

    @property(cc.Node)
    titleList : cc.Node[] = [];

    @property(cc.Node)
    templateEgg : cc.Node = null;

    @property(cc.Node)
    eggList : cc.Node = null;

    @property(cc.Node)
    progressNodeList : cc.Node[] = [];

    @property(cc.Node)
    backNode : cc.Node = null;

    @property(cc.Node)
    partList : cc.Node[] = [];

    @property(cc.Node)
    clickNode : cc.Node[] = [];

    @property(cc.Node)
    pieceNode : cc.Node = null;

    lastPartIndex = 0;

    @property(cc.Node)
    redeemCodeRewardView : cc.Node[] = [];

    @property(cc.Label)
    redeemCodeLab : cc.Label[] = [];


    start () {
        
        if(gameData.redeemCodeUseTimes >= 15){
            this.redeemCodeLab[2].string = "今天兑换次数达上限,明天再来吧";
        }else{
            this.redeemCodeLab[2].string = "今日可兑换次数：" + (15 - gameData.redeemCodeUseTimes) + " / 15"
        }

        if(gameData.getRoleProcessSkin()[17] == 0 && gameData.colorfulPiece[2][0] == 0){
            this.pieceNode.y = cc.winSize.height / 2 - 40;
            this.pieceNode.x = cc.winSize.width / 2 - 100;
            this.clickNode[0].on("touchstart",this.btnClickStart,this);
            this.clickNode[0].on("touchend",this.btnClickEnd,this);
            this.clickNode[1].on("touchstart",this.btnClickStart,this);
            this.clickNode[1].on("touchend",this.btnClickEnd,this);
        }

        for(let i in this.titleList){
            this.titleList[i].y = cc.winSize.height / 2 + 100;
        }

        for(let i in this.progressNodeList){
            this.progressNodeList[i].y = cc.winSize.height / 2 + 130;
        }

        for(let j = 0 ; j < 6 ; j++ ){
            for(let i = 0 ; i < 12 ; i ++){
                let node = cc.instantiate(this.templateEgg);
                node.x = -1800 + 150 * (j % 2) + 300 * i;
                node.y = cc.winSize.height / 2 - 150 * j;
                node.parent = this.eggList;
                node.active = true;
            }
        }

        this.eggWallNode.active = true;
        cc.tween(this.eggWallNode.getChildByName("Background"))
            .to(0.1,{scale : 1})
            .delay(0.1)
            .call(()=>{
                this.eggWallNode.getChildByName("view").active = true;
                this.createEggWall();
                this.createSkinWall();
                for(let i in this.partList){
                    this.partList[i].active = true;
                }
                cc.tween(this.partList[0])
                    .to(0.1,{x : -cc.winSize.width / 2 + 170})
                    .call(()=>{
                        cc.tween(this.partList[1])
                            .to(0.1,{x : -cc.winSize.width/2 + 170})
                            .call(()=>{
                                cc.tween(this.partList[2])
                                    .to(0.1,{x : -cc.winSize.width /2  + 170})
                                    .start();
                            })
                            .start();
                    })
                    .start();
                cc.tween(this.progressNodeList[0])
                    .to(0.2,{y : cc.winSize.height / 2 - 40})
                    .start();

                cc.tween(this.backNode)
                    .to(0.2,{x : -cc.winSize.width / 2 + 60})
                    .start();
            })
            .start();
        cc.tween(this.titleList[0]).to(0.2,{y : cc.winSize.height / 2 - 40})
            .start();
    }

    createEggWall(){
        let pageNumber = Math.ceil(gameData.eggWallDate.length / 4);

        if(pageNumber >= 2){
            this.templateNode.active = true;
        }

        for(let i = 0 ; i < pageNumber - 2 ; i++){
            let node = cc.instantiate(this.templateNode);
            node.active = true;
            node.parent = this.contentNode;
        }

        console.log(gameData.eggWallDate.length);
        for(let j = 0; j < gameData.eggWallDate.length; j ++){
            let index = (j / 4) | 0;
            let node : cc.Node = null;
            if(j >= 1){
                node = cc.instantiate(this.templateItem);
                node.getChildByName("btn1").getComponent(cc.Button).clickEvents.forEach(value => value.customEventData = `${j + 1}`);
                node.getChildByName("btn2").getComponent(cc.Button).clickEvents.forEach(value => value.customEventData = `${j + 1}`);
                node.getChildByName("btn1").active = true;
                node.getChildByName("effect").getChildByName("wh").active = true;
                node.getChildByName("effect").color = cc.color(0,0,0);
                node.getChildByName("btn2").active = false;
                node.getChildByName("get").active = false;
                node.parent = this.contentNode.children[index].getChildByName("list");
            }else{
                this.templateItem.getChildByName("btn1").getComponent(cc.Button).clickEvents.forEach(value => value.customEventData = `${j + 1}`);
                this.templateItem.getChildByName("btn2").getComponent(cc.Button).clickEvents.forEach(value => value.customEventData = `${j + 1}`);
                this.templateItem.getChildByName("btn1").active = true;
                this.templateItem.getChildByName("btn2").active = false;
                this.templateItem.getChildByName("get").active = false;
                this.templateItem.getChildByName("effect").getChildByName("wh").active = true;
                this.templateItem.getChildByName("effect").color = cc.color(0,0,0);
                node = this.templateItem;
            }

            for(let k in gameData.getPetShopData()) {
                if (parseInt(k) < 15) continue;
                if (gameData.eggWallDate[j] && gameData.eggWallDate[j]["reward"] == gameData.getPetShopData()[parseInt(k)]["psname"]) {
                    this.loadPetSkin(parseInt(k) + 1, node.getChildByName("effect"));
                    if (gameData.getPetProcessSkin()[parseInt(k)] == 1) {
                        node.getChildByName("get").active = true;
                        node.getChildByName("btn1").active = false;
                        node.getChildByName("btn2").active = false;
                        node.getChildByName("effect").getChildByName("wh").active = false;
                        node.getChildByName("effect").color = cc.color(255,255,255);
                    } else {
                        let arr = gameData.eggThreadLockData[j];
                        if (arr.indexOf(0) < 0) {
                            node.getChildByName("get").active = false;
                            node.getChildByName("btn1").active = false;
                            node.getChildByName("btn2").active = true;
                        } else {
                            node.getChildByName("get").active = false;
                            node.getChildByName("btn1").active = true;
                            node.getChildByName("btn2").active = false;
                        }
                    }
                }
            }
        }
        this.updateProgress();
    }

    updateProgress(){
        if(this.skinWallNode.active){
            let index1 = [];
            for(let i in gameData.skinThreadLockData){
                let reward = gameData.skinWallDate[parseInt(i)]["reward"];
                for(let j in gameData.getRoleShopData()){
                    if(reward == gameData.getRoleShopData()[parseInt(j)]["rsname"]){
                        if(gameData.getRoleProcessSkin()[parseInt(j)] == 1){
                            index1.push(parseInt(i));
                        }
                    }
                }
            }

            let index2 = [];
            for(let i = 0; i < index1.length ;i++){
                if(index2.indexOf(index1[i]) == -1){
                    index2.push(index1[i]);
                }
            }
            this.skinWallNode.getChildByName("ProgressBar").getComponent(cc.ProgressBar).progress = index2.length / gameData.skinThreadLockData.length;
            this.skinWallNode.getChildByName("ProgressBar").getChildByName("lab").getComponent(cc.Label).string = index2.length + "," + gameData.skinWallDate.length;
        }

        if(this.eggWallNode.active){
            let index1 = [];
            for(let i in gameData.eggThreadLockData){
                let reward = gameData.eggWallDate[parseInt(i)]["reward"];
                for(let j in gameData.getPetShopData()){
                    if(reward == gameData.getPetShopData()[parseInt(j)]["psname"]){
                        if(gameData.getPetProcessSkin()[parseInt(j)] == 1){
                            index1.push(parseInt(i));
                        }
                    }
                }
            }

            let index2 = [];
            for(let i = 0; i < index1.length ;i++){
                if(index2.indexOf(index1[i]) == -1){
                    index2.push(index1[i]);
                }
            }
            this.eggWallNode.getChildByName("ProgressBar").getComponent(cc.ProgressBar).progress = index2.length / gameData.eggThreadLockData.length;
            this.eggWallNode.getChildByName("ProgressBar").getChildByName("lab").getComponent(cc.Label).string = index2.length + "," + gameData.eggThreadLockData.length;
        }

    }


    createSkinWall(){

        let pageNumber = Math.ceil(gameData.skinWallDate.length / 4);

        if(pageNumber >= 2){
            this.skinWallNodeList[0].active = true;
        }

        for(let i = 0 ; i < pageNumber - 2 ; i++){
            let node = cc.instantiate(this.skinWallNodeList[0]);
            node.active = true;
            node.parent = this.skinWallNodeList[2];
        }
        for(let j = 0; j < gameData.skinWallDate.length; j ++){
            let index = (j / 4) | 0;
            let node : cc.Node = null;
            if(j >= 1){
                node = cc.instantiate(this.skinWallNodeList[1]);
                node.getChildByName("btn1").getComponent(cc.Button).clickEvents.forEach(value => value.customEventData = `${j + 1}`);
                node.getChildByName("btn2").getComponent(cc.Button).clickEvents.forEach(value => value.customEventData = `${j + 1}`);
                node.getChildByName("btn1").active = true;
                node.getChildByName("btn2").active = false;
                node.getChildByName("get").active = false;
                node.getChildByName("effect").getChildByName("wh").active = true;
                node.getChildByName("effect").color = cc.color(0,0,0);
                node.parent = this.skinWallNodeList[2].children[index].getChildByName("list");
            }else{
                this.skinWallNodeList[1].getChildByName("btn1").getComponent(cc.Button).clickEvents.forEach(value => value.customEventData = `${j + 1}`);
                this.skinWallNodeList[1].getChildByName("btn2").getComponent(cc.Button).clickEvents.forEach(value => value.customEventData = `${j + 1}`);
                this.skinWallNodeList[1].getChildByName("btn1").active = true;
                this.skinWallNodeList[1].getChildByName("btn2").active = false;
                this.skinWallNodeList[1].getChildByName("effect").getChildByName("wh").active = true;
                this.skinWallNodeList[1].getChildByName("effect").color = cc.color(0,0,0);
                this.skinWallNodeList[1].getChildByName("get").active = false;
                node = this.skinWallNodeList[1];
            }

            for(let k in gameData.getRoleShopData()){
                if(gameData.skinWallDate[j] && gameData.skinWallDate[j]["reward"] == gameData.getRoleShopData()[parseInt(k)]["rsname"]) {
                    let order = gameData.getRoleShopData()[parseInt(k)]["id"];
                    if (j == 0) {
                        if (order < 13) {
                            this.loadSkin("zhujue", node.getChildByName("effect"), order);
                        } else {
                            this.loadSkin("zhujue" + (order + 1), node.getChildByName("effect"), order)
                        }
                    } else {
                        if (order < 13) {
                            this.loadSkin("zhujue", node.getChildByName("effect"), order)
                        } else {
                            this.loadSkin("zhujue" + (order + 1), node.getChildByName("effect"), order)
                        }
                    }

                    if(gameData.getRoleProcessSkin()[order - 1] == 1){
                        node.getChildByName("get").active = true;
                        node.getChildByName("btn1").active = false;
                        node.getChildByName("btn2").active = false;
                        node.getChildByName("effect").getChildByName("wh").active = false;
                        node.getChildByName("effect").color = cc.color(255,255,255);
                    }else{
                        let arr = gameData.skinThreadLockData[j];
                        if(arr.indexOf(0) < 0){
                            node.getChildByName("get").active = false;
                            node.getChildByName("btn1").active = false;
                            node.getChildByName("btn2").active = true;
                        }else{
                            node.getChildByName("get").active = false;
                            node.getChildByName("btn1").active = true;
                            node.getChildByName("btn2").active = false;
                        }
                    }
                }
            }
        }
        this.updateProgress();
    }

    updateItemStatus(name){

        for(let i in this.skinWallNodeList[2].children){
            let index = this.skinWallNodeList[2].children[i];
            for(let j in index.getChildByName("list").children){
                let children = index.getChildByName("list").children[j];
                let order = parseInt(i) + parseInt(j);
                if(gameData.skinWallDate[order]["reward"] == name){
                    children.getChildByName("get").active = true;
                    children.getChildByName("effect").getChildByName("wh").active = true;
                    children.getChildByName("effect").color = cc.color(255,255,255);
                    children.getChildByName("btn1").active = false;
                    children.getChildByName("btn2").active = false;
                }
            }
        }

        for(let i in this.contentNode.children){
            let index = this.contentNode.children[i];
            for(let j in index.getChildByName("list").children){
                let children = index.getChildByName("list").children[j];
                let order = parseInt(i) + parseInt(j);
                if(gameData.eggWallDate[order]["reward"] == name){
                    children.getChildByName("get").active = true;
                    children.getChildByName("effect").getChildByName("wh").active = true;
                    children.getChildByName("effect").color = cc.color(255,255,255);
                    children.getChildByName("btn1").active = false;
                    children.getChildByName("btn2").active = false;
                }
            }
        }

        this.updateProgress();
    }

    loadPetSkin(index,node){
        let name;
        if(index > 10){
           name = "cw" + index;
        }else{
            name = "cw0" + index;
        }
        cc.loader.loadRes("anim/" + name,sp.SkeletonData,(err,res)=>{
            if(err){
                console.log(err);
                return;
            }
            let spk = node.getComponent(sp.Skeleton);
            spk.skeletonData = res;
            spk.defaultAnimation = "daiji";
            spk.setAnimation(0,"daiji",true);
        })
    }

    loadSkin(name,node,index){
        if(index < 13){
            cc.loader.loadRes("anim/" + name,sp.SkeletonData,(err,res)=>{
                if(err){
                    console.log(err);
                    return;
                }
                let spk = node.getComponent(sp.Skeleton);
                spk.skeletonData = res;
                if(index >= 10){
                    spk.defaultSkin = "pf" + index;
                }else{
                    spk.defaultSkin = "pf0" + index;
                }
                spk.defaultAnimation = "animation";
            })
        }else if(index < 14){
            cc.loader.loadRes("anim/" + name,sp.SkeletonData,(err,res)=>{
                if(err){
                    console.log(err);
                    return;
                }
                let spk = node.getComponent(sp.Skeleton);
                spk.skeletonData = res;
                spk.defaultSkin = "pfi1";
                spk.defaultAnimation = "animation";
            })
        }else{
            if(index == 21){
                cc.loader.loadRes("anim/zhujue22_1",sp.SkeletonData,(err,res)=> {
                    if (err) {
                        console.log(err);
                        return;
                    }
                    console.log(index);
                    let spk = node.getComponent(sp.Skeleton);
                    spk.skeletonData = res;
                    spk.defaultAnimation = "animation";
                })
            }else{
                cc.loader.loadRes("anim/" + name,sp.SkeletonData,(err,res)=>{
                    if(err){
                        console.log(err);
                        return;
                    }
                    console.log(index);
                    let spk = node.getComponent(sp.Skeleton);
                    spk.skeletonData = res;
                    spk.defaultAnimation = "animation";
                    if(index == 15){
                        spk.defaultSkin = "pf1";
                    }else if(index == 16){
                        spk.defaultSkin = "default";
                    }else if(index == 17){
                        spk.defaultSkin = "pifu2";
                    }else if(index == 18){
                        spk.defaultSkin = "pf01";
                    }else if(index == 19){
                        spk.defaultSkin = "pf01";
                    }
                })
            }
        }
    }

    partClick(event,data){
        this.partPic[this.lastPartIndex].spriteFrame = this.partPicList[0];
        this.partPic[parseInt(data) - 1].spriteFrame = this.partPicList[1];
        this.lastPartIndex = parseInt(data) - 1;
        if(parseInt(data) == 1){
            this.clearTextLabel();
            this.skinWallNode.active = false;
            this.redeemCodeNode.active = false;
            this.eggWallNode.active = true;

            cc.tween(this.titleList[0]).to(0.1,{
                y : cc.winSize.height / 2 - 40
            }).start();
            cc.tween(this.progressNodeList[0]).to(0.1,{
                y : cc.winSize.height / 2 - 40
            }).call(()=>{
                //提示动画
                for(let i in this.titleList){
                    if(parseInt(i) == 0) continue;
                    this.titleList[i].y = cc.winSize.height / 2 + 100;
                }
                //进度条
                for(let i in this.progressNodeList){
                    if(parseInt(i) == 0) continue;
                    this.progressNodeList[i].y = cc.winSize.height / 2 + 130;
                }
            }).start();
        }

        if(parseInt(data) == 2){
            this.clearTextLabel();
            this.eggWallNode.active = false;
            this.redeemCodeNode.active = false;
            this.skinWallNode.active = true;

            cc.tween(this.titleList[1]).to(0.1,{
                y : cc.winSize.height / 2 - 40
            }).start();
            cc.tween(this.progressNodeList[1]).to(0.1,{
                y : cc.winSize.height / 2 - 40
            }).call(()=>{
                //提示动画
                for(let i in this.titleList){
                    if(parseInt(i) == 1) continue;
                    this.titleList[i].y = cc.winSize.height / 2 + 100;
                }
                //进度条
                for(let i in this.progressNodeList){
                    if(parseInt(i) == 1) continue;
                    this.progressNodeList[i].y = cc.winSize.height / 2 + 130;
                }
            }).start();
        }

        if(parseInt(data) == 3){
            this.skinWallNode.active = false;
            this.eggWallNode.active = false;
            this.redeemCodeNode.active = true;
            cc.tween(this.titleList[2]).to(0.1,{
                y : cc.winSize.height / 2 - 40
            }).call(()=>{
                //提示动画
                for(let i in this.titleList){
                    if(parseInt(i) == 2) continue;
                    this.titleList[i].y = cc.winSize.height / 2 + 100;
                }

                //进度条
                for(let i in this.progressNodeList){
                    this.progressNodeList[i].y = cc.winSize.height / 2 + 130;
                }
            }).start();
        }
        this.updateProgress();
    }

    //展示获取线索界面
    showUnlockView(event,data){
        if(this.skinWallNode.active){
            let arr = [];
            let number = gameData.skinWallDate[parseInt(data) - 1]["keynum"];
            for(let i = 1 ; i < number + 1 ; i++){
                arr.push(gameData.skinWallDate[parseInt(data) - 1]["key" + i]);
            }
            Tool.loadPrefab("prefabs/threadView",(res)=>{
                let view = cc.instantiate(res);
                view.getComponent("threadView").setCallBack(0,number,parseInt(data) - 1,arr,()=>{
                    let arr = gameData.skinThreadLockData[parseInt(data) - 1];
                    if(arr.indexOf(0) < 0){
                        // event.target.parent.getChildByName("get").active = false;
                        event.target.parent.getChildByName("btn2").active = true;
                        event.target.active = false;
                    }
                    this.updateProgress();
                });
                view.parent = this.node;
            })
        }

        if(this.eggWallNode.active){
            let arr = [];
            let number = gameData.eggWallDate[parseInt(data) - 1]["keynum"];
            for(let i = 1 ; i < number + 1 ; i++){
                arr.push(gameData.eggWallDate[parseInt(data) - 1]["key" + i]);
            }
            Tool.loadPrefab("prefabs/threadView",(res)=>{
                let view = cc.instantiate(res);
                view.getComponent("threadView").setCallBack(1,number,parseInt(data) - 1,arr,()=>{
                    let arr = gameData.eggThreadLockData[parseInt(data) - 1];
                    if(arr.indexOf(0) < 0){
                        // event.target.parent.getChildByName("get").active = false;
                        // let spk = event.target.parent.getChildByName("effect").getComponent(sp.Skeleton);
                        // spk.setAnimation(0,"eggs1",false);
                        // spk.setCompleteListener(()=>{
                        //     this.loadPetSkin(15 + parseInt(data), event.target.parent.getChildByName("effect"));
                        // });
                        event.target.parent.getChildByName("btn2").active = true;
                        event.target.active = false;
                    }
                    this.updateProgress();
                });
                view.parent = this.node;
            })
        }
        
    }

    callback = null;
    setCallBack(callback){
        this.callback = callback;
    }

    backHome(){
        this.node.destroy();
        if(this.callback != null){
            this.callback();
        }
    }

    //查看线索
    showLockThread(event,data){
        if(this.skinWallNode.active){
            let arr = [];
            let number = gameData.skinWallDate[parseInt(data) - 1]["keynum"];
            for(let i = 1 ; i < number + 1 ; i++){
                arr.push(gameData.skinWallDate[parseInt(data) - 1]["key" + i]);
            }
            Tool.loadPrefab("prefabs/threadView",(res)=>{
                let view = cc.instantiate(res);
                view.getComponent("threadView").setCallBack(0,number,parseInt(data) - 1,arr,()=>{

                });
                view.parent = this.node;
            })
        }

        if(this.eggWallNode.active){
            let arr = [];
            let number = gameData.eggWallDate[parseInt(data) - 1]["keynum"];
            for(let i = 1 ; i < number + 1 ; i++){
                arr.push(gameData.eggWallDate[parseInt(data) - 1]["key" + i]);
            }
            Tool.loadPrefab("prefabs/threadView",(res)=>{
                let view = cc.instantiate(res);
                view.getComponent("threadView").setCallBack(1,number,parseInt(data) - 1,arr,()=>{

                });
                view.parent = this.node;
            })
        }
    }


    curTextLabel = "";
    inputLabelText(event,data){
        AudioManage.playSFX(soundList.uiClick);
        if(parseInt(data) == 11){
            this.curTextLabel = "";
        }else{
            if(this.curTextLabel.length >= 8){
                return;
            }
            if(parseInt(data) < 10){
                this.curTextLabel += data;
            }else if(parseInt(data) == 10){
                this.curTextLabel += 0;
            }
        }
        if(this.curTextLabel.length == 0){
            this.redeemCodeLab[1].node.active = true;
        }else{
            this.redeemCodeLab[1].node.active = false;
        }
        console.log(this.curTextLabel);
        this.redeemCodeLab[0].string = this.curTextLabel;
    }

    judgeInput(){

        if(gameData.redeemCodeUseTimes >= 15){
            mainManage.createToast("今天兑换次数达上限,明天再来吧");
            return
        }
        gameData.redeemCodeUseTimes++;
        gameData.saveLotteryData();

        if(gameData.redeemCodeUseTimes >= 15){
            this.redeemCodeLab[2].string = "今天兑换次数达上限,明天再来吧";
        }else{
            this.redeemCodeLab[2].string = "今日可兑换次数：" + (15 - gameData.redeemCodeUseTimes) + " / 15"
        }


        let flag = false;
        if (this.curTextLabel.length == 4){
            flag = this.popularRedeem();
        }else if (this.curTextLabel.length == 5){
            flag = this.conditionalRedeem();
        }
        if (!flag) {
            // 服务器三种兑换码
            this.randomRedeem();
        }
    }

    exchangeReward(){
        this.redeemCodeNodeList[0].active = true;
        let spk = this.redeemCodeNodeList[1].getComponent(sp.Skeleton);
        spk.setAnimation(0,"eggs1",false);
        spk.setCompleteListener(()=>{
            this.redeemCodeNodeList[2].active = true;
        })
    }

    getReward(){
        gameData.addSinglePumpkin(1);
        mainManage.createToast("获得一个苹果");
        this.redeemCodeNodeList[0].active = false;
    }

    goodsName;

    cancelGetReward(){
        this.redeemCodeRewardView[0].active = false;
        if (gameData.curRedeemSuccessType == 0){
            this.redeemCodeRewardView[1].children[gameData.curRedeemSuccessId-1].active = false;
        }else if (gameData.curRedeemSuccessType == 1){
            this.redeemCodeRewardView[2].children[gameData.curRedeemSuccessId-1].active = false;
        }else if (gameData.curRedeemSuccessType == 2){
            this.redeemCodeRewardView[4].active = false;
        }else if (gameData.curRedeemSuccessType == 3){
            this.redeemCodeRewardView[5].active = false;
        }else if (gameData.curRedeemSuccessType == 4){
            this.redeemCodeRewardView[3].active = false;
        }
    }

    getRewardOK(){

        if(this.curRewardTypeWithNumber[2] != -1){

        }else{
            gameData.conditionalRedeemStatus[this.curRewardIndex] = 1;
            gameData.saveAllRedeemStatus("conditionalRedeemStatus",gameData.conditionalRedeemStatus);
            this.updateItemStatus(gameData.getPopularRedeemData()[this.curRewardIndex].name);
        }
        if(this.curRewardTypeWithNumber[0] == Rewards.REWARD_PET){
            gameData.savePetSkin(this.curRewardTypeWithNumber[1]);
            mainManage.createToast( "成功获得宠物" + this.goodsName);
        }else if(this.curRewardTypeWithNumber[0] == Rewards.REWARD_ROLE){
            gameData.saveRoleSkin(this.curRewardTypeWithNumber[1]);
            mainManage.createToast( "成功获得皮肤" + this.goodsName)
        }else if(this.curRewardTypeWithNumber[0] == Rewards.REWARD_APPLE){
            gameData.addSinglePumpkin(this.curRewardTypeWithNumber[1]);
            mainManage.createToast( "成功获得苹果x" + this.curRewardTypeWithNumber[1])
        }else if(this.curRewardTypeWithNumber[0] == Rewards.LOTTERY_TICKET){
            if(typeof this.curRewardTypeWithNumber[1] == "number"){
                gameData.lotteryTicket += this.curRewardTypeWithNumber[1];
            }
            gameData.saveLotteryData();
            mainManage.createToast( "成功获得奖券x" + this.curRewardTypeWithNumber[1])
        }else if(this.curRewardTypeWithNumber[0] == Rewards.PURPLE_PIECE){
            gameData.colorfulPiece[0][6] = 1;
            gameData.saveColorfulPiece();
            mainManage.createToast( "成功获得紫色碎片x" + this.curRewardTypeWithNumber[1])
        }
        this.updateItemStatus(gameData.getPopularRedeemData()[this.curRewardIndex].name);

        this.redeemCodeRewardView[0].active = false;
        if (gameData.curRedeemSuccessType == 0){
            this.redeemCodeRewardView[1].children[gameData.curRedeemSuccessId-1].active = false;
        }else if (gameData.curRedeemSuccessType == 1){
            this.redeemCodeRewardView[2].children[gameData.curRedeemSuccessId-1].active = false;
        }else if (gameData.curRedeemSuccessType == 2){
            this.redeemCodeRewardView[4].active = false;
        }else if (gameData.curRedeemSuccessType == 3){
            this.redeemCodeRewardView[5].active = false;
        }else if (gameData.curRedeemSuccessType == 4){
            this.redeemCodeRewardView[3].active = false;
        }else if (gameData.curRedeemSuccessType == 5){
            this.redeemCodeRewardView[6].active = false;
        }
    }

    // 通用兑换码
    popularRedeem(){
        return this.pppredeemCode(this.curTextLabel);
    }

    rightCode;
    // 条件兑换码
    conditionalRedeem(){
        console.log("条件型");
        // 判断兑换码是否存在
        let isKeyExists = false;
        let data = gameData.getConditionalRedeemData();
        for (let i in gameData.getConditionalRedeemData()) {
            if (this.curTextLabel == data[i].code) {
                isKeyExists = true;
            }
        }

        let state = false;
        if(isKeyExists) {
            // 判断录屏状态
            let recorderState = Tool.getData("recorderShareSuccess");
            let tmp;
            if( typeof recorderState == "string"){
                tmp = (recorderState == "true" ? true : false);
            }else if(typeof recorderState == "boolean"){
                tmp = recorderState;
            }
            if (tmp){
                state = this.cccredeemCode(this.curTextLabel);
            }else {
                mainManage.createToast("发布录屏后才能使用此兑换码哦");
                state = true;
                this.clearTextLabel();
            }
        }
        return state;
    }

    // 2500
    // 判断输入的第一二位数
    // 随机一次性兑换码 与服务器交互
    randomRedeem(data){

        if (data.status == -9){
            mainManage.createToast("这个兑换码是错误的哦");
            this.clearTextLabel();
        }else {
            if (data.isUse) {
                mainManage.createToast("已经使用过这个兑换码了哦");
                this.clearTextLabel();
            } else {

                if (data.requires.length != 0) {
                    for (let r of data.requires) {
                        let {type, value, num} = r;
                        let recordTmp = false;
                        // TODO 判断前置条件
                        if (type == Require.RECORD_SCREEN) {
                            let recorderState = Tool.getData("recorderShareSuccess");
                            if( typeof recorderState == "string"){
                                recordTmp = (recorderState == "true" ? true : false);
                            }else if(typeof recorderState == "boolean"){
                                recordTmp = recorderState;
                            }
                        }
                        if (type == Require.RECORD_SCREEN && !recordTmp) {
                            mainManage.createToast("发布录屏后才能使用此兑换码哦");
                            this.clearTextLabel();
                            return;
                        }else {
                            Tool.saveData("recorderShareSuccess",false);
                        }
                    }
                }
                for(let r of data.rewards) {
                    // type:奖励类型
                    // value:奖励ID
                    // num:奖励数量
                    let {type, value, num} = r;
                    // TODO 给奖励
                    if (type == Rewards.REWARD_PET) {
                        this.curRewardTypeWithNumber = [Rewards.REWARD_PET, value - 1,this.curTextLabel];
                        this.givePet(value);
                    } else if (type == Rewards.REWARD_ROLE) {
                        this.curRewardTypeWithNumber =  [Rewards.REWARD_ROLE,value - 1,this.curTextLabel];
                        this.giveRole(value);
                    }else if (type == Rewards.REWARD_APPLE){
                        this.curRewardTypeWithNumber =  [Rewards.REWARD_APPLE,num,this.curTextLabel];
                        this.giveApple(num);
                    }else if(type == Rewards.LOTTERY_TICKET){
                        this.curRewardTypeWithNumber =  [Rewards.LOTTERY_TICKET,num,this.curTextLabel];
                        this.giveLottery(num);
                    } else if(type == Rewards.REWARD_PET_ROLE){
                        this.giveRoleWithPet();
                    }else if(type == Rewards.PURPLE_PIECE){
                        this.curRewardTypeWithNumber =  [Rewards.PURPLE_PIECE,num,this.curTextLabel];
                        this.givePurplePiece();
                    }
                }
            }
        }
    }

    curRewardTypeWithNumber = [0,0,0];
    curRewardIndex = 0;

    pppredeemCode(inputLabel){
        return this.compareCode(inputLabel,gameData.getPopularRedeemData(),gameData.popularRedeemStatus,(i)=>{
            // 改变状态
            gameData.popularRedeemStatus[i] = 1;
            gameData.saveAllRedeemStatus("popularRedeemStatus",gameData.popularRedeemStatus);
        });
    }

    cccredeemCode(inputLabel){
        return this.compareCode(inputLabel,gameData.getConditionalRedeemData(),gameData.conditionalRedeemStatus,(i)=>{
            // 改变状态
            Tool.saveData("rebackIsSuccess",1);
        },()=>{
            Tool.saveData("rebackIsSuccess",1);
        },()=>{
            Tool.saveData("rebackIsSuccess",1);
        });
    }

    compareCode(inputLabel,getData,redeemStatus,callback?,failedCallback?,closeCallback?){
        let showFail = false;
        for (let i in getData){
            let data = getData;
            if(inputLabel == data[i].code){
                showFail = false;
                if (redeemStatus[i] == 0){
                    console.log("正确的兑换码");
                    this.clearTextLabel();
                    // 宠物
                    for(let j in gameData.getPetShopData()){
                        if(gameData.getPetShopData()[j]["psname"] == data[i].name){
                            if(gameData.getPetProcessSkin()[j] == 1){
                                mainManage.createToast("勇者大人已经拥有此奖励啦！");
                            }else{
                                gameData.getCurSuccessRedeemInfo(j,0);
                                // gameData.savePetSkin(j);
                                this.curRewardTypeWithNumber = [Rewards.REWARD_PET,parseInt(j),-1];
                                this.curRewardIndex = parseInt(i);
                                mainManage.createToast("兑换码使用成功！");
                                this.scheduleOnce(()=>{
                                    this.redeemCodeRewardView[0].getChildByName("mask").getChildByName("cancel").active = false;
                                    this.redeemCodeRewardView[0].active = true;
                                    this.scheduleOnce(()=>{
                                        this.redeemCodeRewardView[0].getChildByName("mask").getChildByName("cancel").active = true;
                                    },2);
                                    this.redeemCodeRewardView[1].children[parseInt(gameData.getPetShopData()[parseInt(j)].id) - 1].active = true;
                                },0.2)
                            }
                        }
                    }
                    // 人物
                    for(let j in gameData.getRoleShopData()){
                        if(gameData.getRoleShopData()[j]["rsname"] == data[i].name){
                            if(gameData.getRoleProcessSkin()[j] == 1){
                                mainManage.createToast("勇者大人已经拥有此奖励啦！");
                            }else{
                                gameData.getCurSuccessRedeemInfo(j,1);
                                this.curRewardTypeWithNumber = [Rewards.REWARD_ROLE,parseInt(j),-1];
                                this.curRewardIndex = parseInt(i);
                                mainManage.createToast("兑换码使用成功！");
                                this.scheduleOnce(()=>{
                                    this.redeemCodeRewardView[0].getChildByName("mask").getChildByName("cancel").active = false;
                                    this.redeemCodeRewardView[0].active = true;
                                    this.scheduleOnce(()=>{
                                        this.redeemCodeRewardView[0].getChildByName("mask").getChildByName("cancel").active = true;
                                    },2);
                                    this.redeemCodeRewardView[2].children[parseInt(gameData.getRoleShopData()[parseInt(j)].id) - 1].active = true;
                                },0.2)
                            }
                        }
                    }
                    // 苹果
                    if(data[i].name.indexOf("apple") > -1){
                        gameData.getCurSuccessRedeemInfo(i,2);
                        // gameData.addSinglePumpkin(100);
                        this.curRewardIndex = parseInt(i);
                        this.curRewardTypeWithNumber = [Rewards.REWARD_APPLE,100,-1];
                    }

                    if(data[i].name.indexOf("龙珠") > -1){
                        if(gameData.colorfulPiece[2][6] == 0 && gameData.getRoleProcessSkin()[17] == 0){
                            this.updateItemStatus(data[i].name);
                            gameData.colorfulPiece[2][6] = 1;
                            gameData.saveColorfulPiece();
                            gameData.getCurSuccessRedeemInfo(i,4);
                            this.scheduleOnce(()=>{
                                this.redeemCodeRewardView[0].getChildByName("mask").getChildByName("cancel").active = false;
                                this.redeemCodeRewardView[0].active = true;
                                this.scheduleOnce(()=>{
                                    this.redeemCodeRewardView[0].getChildByName("mask").getChildByName("cancel").active = true;
                                },2);
                                this.redeemCodeRewardView[3].active = true;
                            },0.2)
                        }else{
                            mainManage.createToast("该物品已经解锁,无法兑换");
                        }
                    }

                    // 改变状态
                    if (callback){
                        callback(i);
                    }
                    this.goodsName = data[i].name;
                }else if (redeemStatus[i] == 1){
                    mainManage.createToast("已经使用过这个兑换码了哦");
                    if (failedCallback){
                        failedCallback();
                    }
                }else if (redeemStatus[i] == 2){
                    mainManage.createToast("这个兑换码已经失效了哦");
                    if (closeCallback){
                        closeCallback();
                    }
                }break;
            }else{
                showFail = true;
            }
        }
        return !showFail;
    }

    clearTextLabel(){
        // this.redeemCodeLab[2].node.active = true;
        this.curTextLabel = "";
        this.redeemCodeLab[0].string = "输入兑换码...";
    }


    getCurSuccessRedeemInfo(curID,type){
        console.log("获取奖励信息");
        if (type == 0){


        }else if (type == 1){

        }else if (type == 2){

        }
    }

    givePet(petID){
        // 宠物
        for(let i in gameData.getPetShopData()){
            if(gameData.getPetShopData()[i]["id"] == petID){
                this.goodsName = gameData.getPetShopData()[i]["psname"];
                if(gameData.getPetProcessSkin()[i] == 1){
                    mainManage.createToast("勇者大人已经拥有此奖励啦！");
                }else{
                    mainManage.createToast("兑换码使用成功！");
                    gameData.getCurSuccessRedeemInfo(i,1);
                    this.scheduleOnce(()=>{
                        this.redeemCodeRewardView[0].getChildByName("mask").getChildByName("cancel").active = false;
                        this.redeemCodeRewardView[0].active = true;
                        this.scheduleOnce(()=>{
                            this.redeemCodeRewardView[0].getChildByName("mask").getChildByName("cancel").active = true;
                        },2);
                        this.redeemCodeRewardView[1].children[gameData.curRedeemSuccessId-1].active = true;
                    },0.2)
                }
            }
        }
        this.clearTextLabel();
    }

    giveRole(roleID){
        // 人物
        for (let i in gameData.getRoleShopData()){
            if(gameData.getRoleShopData()[i]["id"] == roleID){
                this.goodsName = gameData.getRoleShopData()[i]["rsname"];
                if(gameData.getRoleProcessSkin()[i] == 1){
                    mainManage.createToast("勇者大人已经拥有此奖励啦！");
                }else{
                    gameData.getCurSuccessRedeemInfo(i,0);
                    mainManage.createToast("兑换码使用成功！");
                    this.scheduleOnce(()=>{
                        this.redeemCodeRewardView[0].getChildByName("mask").getChildByName("cancel").active = false;
                        this.redeemCodeRewardView[0].active = true;
                        this.scheduleOnce(()=>{
                            this.redeemCodeRewardView[0].getChildByName("mask").getChildByName("cancel").active = true;
                        },2);
                        this.redeemCodeRewardView[2].children[gameData.curRedeemSuccessId-1].active = true;
                    },0.2)
                }
            }
        }

        this.clearTextLabel();
    }

    giveApple(num){
        // 苹果
        gameData.getCurSuccessRedeemInfo(0,2);
        this.goodsName = "苹果x" + num + "个";
        mainManage.createToast("兑换码使用成功！");
        this.scheduleOnce(()=>{
            this.redeemCodeRewardView[0].getChildByName("mask").getChildByName("cancel").active = false;
            this.redeemCodeRewardView[0].active = true;
            this.scheduleOnce(()=>{
                this.redeemCodeRewardView[0].getChildByName("mask").getChildByName("cancel").active = true;
            },2);
            this.redeemCodeRewardView[4].active = true;
        },0.2);
        this.clearTextLabel();
    }

    giveLottery(num){
        this.goodsName = "奖券x" + num + "个";
        gameData.getCurSuccessRedeemInfo(0,3);
        this.redeemCodeRewardView[5].children[0].getComponent(cc.Label).string = "奖券x" + num;
        mainManage.createToast("兑换码使用成功!");
        this.scheduleOnce(()=>{
            this.redeemCodeRewardView[0].getChildByName("mask").getChildByName("cancel").active = false;
            this.redeemCodeRewardView[0].active = true;
            this.scheduleOnce(()=>{
                this.redeemCodeRewardView[0].getChildByName("mask").getChildByName("cancel").active = true;
            },2);
            this.redeemCodeRewardView[5].active = true;
        },0.2);
        this.clearTextLabel();
    }

    givePurplePiece(){
        this.goodsName = "紫色碎片1个";
        gameData.getCurSuccessRedeemInfo(0,5);
        this.redeemCodeRewardView[5].children[0].getComponent(cc.Label).string = "紫色碎片1个";
        mainManage.createToast("兑换码使用成功!");
        this.scheduleOnce(()=>{
            this.redeemCodeRewardView[0].getChildByName("mask").getChildByName("cancel").active = false;
            this.redeemCodeRewardView[0].active = true;
            this.scheduleOnce(()=>{
                this.redeemCodeRewardView[0].getChildByName("mask").getChildByName("cancel").active = true;
            },2);
            this.redeemCodeRewardView[6].active = true;
        },0.2);
        this.clearTextLabel();
    }


    giveRoleWithPet(){
        for(let i in gameData.roleSkinList){
            gameData.roleSkinList[i] = 1;
        }
        for(let i in gameData.petSkinList){
            gameData.petSkinList[i] = 1;
        }
        Tool.saveData("petSkin",JSON.stringify(gameData.petSkinList));
        Tool.saveData("roleSkin",JSON.stringify(gameData.roleSkinList));
        mainManage.createToast("已解锁所有皮肤和宠物");

        // YchlStatistic.getRedeemCDKeyUse(this.curTextLabel + "", (data) => {
        //
        // });
        //

        for(let i in this.skinWallNodeList[2].children){
            let index = this.skinWallNodeList[2].children[i];
            for(let j in index.getChildByName("list").children){
                let children = index.getChildByName("list").children[j];
                // let order = parseInt(i) + parseInt(j);
                children.getChildByName("get").active = true;
                children.getChildByName("effect").getChildByName("wh").active = false;
                children.getChildByName("effect").color = cc.color(255,255,255);
                children.getChildByName("btn1").active = false;
                children.getChildByName("btn2").active = false;
            }
        }

        for(let i in this.contentNode.children){
            let index = this.contentNode.children[i];
            for(let j in index.getChildByName("list").children){
                let children = index.getChildByName("list").children[j];
                // let order = parseInt(i) + parseInt(j);
                children.getChildByName("get").active = true;
                children.getChildByName("effect").getChildByName("wh").active = false;
                children.getChildByName("effect").color = cc.color(255,255,255);
                children.getChildByName("btn1").active = false;
                children.getChildByName("btn2").active = false;
            }
        }

        this.updateProgress();
        this.clearTextLabel();
    }


    clickPicaTimes = 0;
    btnClickStart(event){
        this.clickPicaTimes++;
        AudioManage.playSFX(soundList.uiClick);
        event.target.getChildByName("lab").active = true;
        event.target.scale = 1.2;

    }

    btnClickEnd(event){
        event.target.scale = 1;
        event.target.getChildByName("lab").active = false;
        if(this.clickPicaTimes == 10){
            this.clickPicaTimes = 0;
            this.pieceNode.active = true;
            this.pieceNode.zIndex = 500;
            cc.tween(this.pieceNode).to(0.5,{
                position : cc.v2(0,0)
            }).call(()=>{
                let spk =  event.target.getChildByName("effect").getComponent(sp.Skeleton);
                spk.setAnimation(0,"pikachu1",false);
                spk.addAnimation(0,"pikachu_daiji",true);
                if(gameData.getRoleProcessSkin()[17] == 0 && gameData.colorfulPiece[2][0] == 0){
                    Tool.loadPrefab("prefabs/callDragonBall",(res)=>{
                        let view = cc.instantiate(res);
                        view.getComponent("callDragonBall").setCallBack(1,false,()=>{
                            for(let i in this.clickNode){
                                this.clickNode[i].off("touchstart",this.btnClickStart,this);
                                this.clickNode[i].off("touchend",this.btnClickEnd,this);
                            }
                            this.pieceNode.active = false;
                        },()=>{
                            this.pieceNode.active = false;
                            this.pieceNode.y = cc.winSize.height / 2 - 40;
                            this.pieceNode.x = cc.winSize.width / 2 - 100;
                        });
                        view.parent = cc.find("Canvas");
                    })
                }
            }).start();
        }
    }

    // update (dt) {}
}
